package com.thread;

/**
 * 线程打印奇数和偶数
 */
public class Demo2 implements Runnable {

    private int i = 0;

    public synchronized int getValue() {
        return i;
    }

    public  void add() {
        i = i + 1;
    }


    public static void main(String[] args) throws InterruptedException {
        Demo2 s = new Demo2();
        Thread a = new Thread(s, "线程a");
        Thread b = new Thread(s, "线程b");
        a.start();
        b.start();

        while (true) {
            if (s.getValue() > 20) {
                System.out.println("stop");
                a.stop();
                b.stop();
                break;
            }
        }
    }

    @Override
    public void run() {
        while (true) {
            String name = Thread.currentThread().getName();
            if (name.equals("线程a") && getValue() % 2 == 1) {
                System.out.println(Thread.currentThread().getName() + "线程打印奇数：" + i);
                add();
            }
            if (name.equals("线程b") && getValue() % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + "线程打印偶数：" + i);
                add();
            }
        }
    }
}
